package com.zat.mes.andrmes.dofun.work

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.media.RingtoneManager
import android.text.Html
import android.text.InputType
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.data.PackBean
import com.zat.mes.andrmes.data.PaiZaiBean
import com.zat.mes.andrmes.data.PaiZaiDetailBean
import com.zat.mes.andrmes.dofun.QrScanActivity
import com.zat.mes.andrmes.dofun.work.adapter.UpdatePackQtyDetailAdapter
import com.zat.mes.andrmes.dofun.work.vm.GetPackModel
import com.zat.mes.andrmes.dofun.work.vm.WorkRecordViewModel
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.DisplayUtil
import com.zat.mes.andrmes.utils.ReadCardUtils
import com.zat.mes.andrmes.utils.SystemActivityUtil
import com.zat.mes.andrmes.utils.showToast
import kotlinx.android.synthetic.main.activity_in_house.*
import kotlinx.android.synthetic.main.activity_motor_work_record.*
import kotlinx.android.synthetic.main.activity_update_pack_qty.*
import kotlinx.android.synthetic.main.activity_update_pack_qty.btnScanInhouse
import kotlinx.android.synthetic.main.dialog_upate_qty.view.*
import kotlinx.android.synthetic.main.layout_title.*
import permissions.dispatcher.*

/**
 * 修改裁片包数量
 */
@RuntimePermissions
class UpdatePackQtyActivity : BaseActivity() {


    //U口读卡器,类似于外接键盘
    private var readCardUtils: ReadCardUtils? = null
    private var recordViewModel: WorkRecordViewModel? = null
    private var packId: Long = -1
    private var getPackModel: GetPackModel? = null
    var paiZaiBean:PaiZaiBean?=null
    var paiZaiBean1:PaiZaiBean?=null
    var paiZaiBean2:PaiZaiBean?=null
    var flag=0
    var qrCode:String ?=null
    var scrapsFlag="no"
    override fun init() {
        initView()
        initData()
    }


    private fun initData() {
        //读卡器声明
        readCardUtils = ReadCardUtils()
        initCardReader()

        recordViewModel = ViewModelProvider(this).get(WorkRecordViewModel::class.java)
        recordViewModel?.getPackData()?.observe(this, androidx.lifecycle.Observer {
            closeLoading()
            if (it == null) {
                showToast(getString(R.string.text_not_find_pack))
            } else {
                packId = it.packId
                //setText(it)
                getPackModel?.paiZaiInfo(packId.toString())
            }

        })

        getPackModel = ViewModelProvider(this).get(GetPackModel::class.java)
        getPackModel?.getPackUpdate()?.observe(this, Observer {
            closeLoading()
            showToast(it)
            requestData()
        })
        getPackModel?.getPack()?.observe(this, Observer {
            closeLoading()
            if (it != null) {
                setText(it)
            }
        })
        getPackModel?.getPaiZaiData()?.observe(this, Observer {
            closeLoading()
            if(flag==0)
            setPaiZaiBeanData(it)
            else if(flag==1)
                setPaiZaiBeanData1(it)
            else if(flag==2)
                setPaiZaiBeanData2(it)

        })
        getPackModel?.getPaiZaiProducedQty()?.observe(this, Observer {
            showToast(if (it!=null && it.isNotEmpty()) it else "设置成功")
            getPackModel?.paiZaiInfo(qrCode!!)

        })
        getPackModel?.getTranPaiZaiProducedQtyData()?.observe(this,Observer {
            showToast(if (it!=null && it.isNotEmpty()) it else "操作成功")
        })



    }


    fun setPaiZaiBeanData(bean: PaiZaiBean){
        paiZaiBean=bean
        codeTV.text="包号："+bean.code
        orderNoTV.text="计划号："+bean.orderNo
        styleNoTV.text="款号："+bean.styleNo
        colorSizeTV.text="颜色/尺码："+bean.color+"/"+bean.size
        qtyTV.text="织片数量："+bean.producedQty
        workEmpNameTV.text="操作工："+bean.workEmpName
      //  scrapsFlagTV.text="是否为残片："+bean.scrapsFlag
        detailListTV.text= Html.fromHtml("<u>"+"物料明细"+"</u>")
        detailListTV.setOnClickListener {
            var view=LayoutInflater.from(this).inflate(R.layout.layout_update_pack_qty_detail_list,null)
            val dataRV=view.findViewById<RecyclerView>(R.id.detailsListRV)
            dataRV.layoutManager = LinearLayoutManager(this)
            val updatePackQtyDetailAdapter = UpdatePackQtyDetailAdapter(R.layout.item_update_pack_qty_detail)
            dataRV.adapter = updatePackQtyDetailAdapter
            view.findViewById<CheckBox>(R.id.checkbox).visibility=View.GONE
            updatePackQtyDetailAdapter.setNewInstance(paiZaiBean?.detailList as MutableList<PaiZaiDetailBean>)
            val dialog=AlertDialog.Builder(this).setTitle("物料明细").setView(view).create()
            dialog.show()
        }
        btnUpdatePackQty.visibility=View.VISIBLE
        tableLayout.visibility=View.VISIBLE
        setPaiZaiBeanData1(null)
        setPaiZaiBeanData2(null)
    }
     fun setPaiZaiBeanData1(bean: PaiZaiBean?){
        paiZaiBean1=bean
        codeTV1.text= bean?.code ?: ""
        orderNoTV1.text= bean?.orderNo ?: ""
        styleNoTV1.text= bean?.styleNo ?: ""
        colorSizeTV1.text=if (bean==null) "" else (bean.color+"/"+bean.size)
        qtyTV1.text= bean?.producedQty?.toString() ?: ""
        workEmpNameTV1.text= bean?.workEmpName ?: ""
       // scrapsFlagTV1.text= bean?.scrapsFlag ?: ""
        detailListTV1.text=if (bean==null) "" else Html.fromHtml("<u>"+"主包物料明细"+"</u>")

        detailListTV1.setOnClickListener {
            if (paiZaiBean1==null) return@setOnClickListener
            var view=LayoutInflater.from(this).inflate(R.layout.layout_update_pack_qty_detail_list,null)
            val dataRV=view.findViewById<RecyclerView>(R.id.detailsListRV)
            dataRV.layoutManager = LinearLayoutManager(this)
            val updatePackQtyDetailAdapter = UpdatePackQtyDetailAdapter(R.layout.item_update_pack_qty_detail)
            dataRV.adapter = updatePackQtyDetailAdapter
            view.findViewById<CheckBox>(R.id.checkbox).visibility=View.GONE
            updatePackQtyDetailAdapter.setNewInstance(paiZaiBean1?.detailList as MutableList<PaiZaiDetailBean>)
            val dialog=AlertDialog.Builder(this).setTitle("主包物料明细").setView(view).create()
            dialog.show()
        }
    }

     fun setPaiZaiBeanData2(bean: PaiZaiBean?){
        paiZaiBean2=bean
        codeTV2.text= bean?.code ?: ""
        orderNoTV2.text= bean?.orderNo ?: ""
        styleNoTV2.text= bean?.styleNo ?: ""
        colorSizeTV2.text=if (bean==null) "" else bean.color+"/"+bean.size
        qtyTV2.text= bean?.producedQty?.toString() ?: ""
        workEmpNameTV2.text= bean?.workEmpName ?: ""
      //  scrapsFlagTV2.text= bean?.scrapsFlag ?: ""
        detailListTV2.text= if (bean==null) "" else Html.fromHtml("<u>"+"配包物料明细"+"</u>")

          detailListTV2.setOnClickListener {
              if (paiZaiBean2==null) return@setOnClickListener
              var view=LayoutInflater.from(this).inflate(R.layout.layout_update_pack_qty_detail_list,null)
            val dataRV=view.findViewById<RecyclerView>(R.id.detailsListRV)
            dataRV.layoutManager = LinearLayoutManager(this)
            val updatePackQtyDetailAdapter = UpdatePackQtyDetailAdapter(R.layout.item_update_pack_qty_detail)
            dataRV.adapter = updatePackQtyDetailAdapter
              view.findViewById<CheckBox>(R.id.checkbox).visibility=View.GONE
              updatePackQtyDetailAdapter.setNewInstance(paiZaiBean2?.detailList as MutableList<PaiZaiDetailBean>)
            val dialog=AlertDialog.Builder(this).setTitle("配包物料明细").setView(view).create()
            dialog.show()
        }
    }



    /**
     * 设置text
     */
    private fun setText(it: PackBean) {
        tvPackNoPackQty.text = getString(R.string.text_pack_no) + "：" + it.packNO
        tvNamePackQty.text = it.productName
        tvStyleNoPackQty.text = getString(R.string.text_style) + "：" + it.styleNO
        tvGanghaoPackQty.text= "缸号"+"："+it.remark1
        tvQtyPackQty.text = getString(R.string.text_amount) + "：" + it.quantity
        tvWeightPackQty.text = "重量"+"："+it.remark2
        if (!TextUtils.isEmpty(it.remark)) {
            tvRemarkPackQty.text = getString(R.string.remark) + "：" + it.remark
        }
    }

    /**
     * 初始化view
     */
    private fun initView() {
        setContentView(R.layout.activity_update_pack_qty)
        tVtitle.text = getString(R.string.title_update_pack_qty)
        rlReturnTitle.visibility = View.VISIBLE
        rlRightComm.visibility = View.INVISIBLE
        val ivRight = ImageView(this)
        ivRight.setImageResource(R.mipmap.ico_right_scan)
        rlRightComm.addView(ivRight)
        val layoutParams: RelativeLayout.LayoutParams =
            ivRight.layoutParams as RelativeLayout.LayoutParams
        layoutParams.rightMargin = DisplayUtil.dip2px(this, 10f)
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT)
        rlReturnTitle.setOnClickListener { finish() }
        rlRightComm.setOnClickListener {
            showCameraWithPermissionCheck()
        }

        btnScanInhouse.setOnClickListener {
            flag=0
            scrapsFlag="no"
            showCameraWithPermissionCheck()
        }
        btnScanInhouse1.setOnClickListener {
            flag=0
            scrapsFlag="yes"
            showCameraWithPermissionCheck()
        }
        zhuScanTV.setOnClickListener {
            flag=1
            showCameraWithPermissionCheck()
        }
        peiScanTV.setOnClickListener {
            flag=2
            showCameraWithPermissionCheck()
        }
        transQtyTV.setOnClickListener {
            if (paiZaiBean1==null || paiZaiBean2==null){
                showToast("请完成主配包扫码")
                return@setOnClickListener
            }
            var qty=transQtyET.text.toString()
            if (qty.isEmpty()){
                showToast("请输入需转移的数量")
                return@setOnClickListener
            }
            var mainPaiZaiId:String?=null
            var vicePaiZaiId:String?=null
            if (flag == 1) {
                mainPaiZaiId=paiZaiBean1?.id.toString()
                vicePaiZaiId=paiZaiBean2?.id.toString()
            }else if (flag == 2) {
                mainPaiZaiId=paiZaiBean2?.id.toString()
                vicePaiZaiId=paiZaiBean1?.id.toString()
            }
            getPackModel?.tranPaiZaiProducedQty(mainPaiZaiId!!,qty, vicePaiZaiId!!)

        }


        btnUpdatePackQty.setOnClickListener {

//            if (packId != -1L) {
//                val alertDialog = AlertDialog.Builder(UpdatePackQtyActivity@ this)
//                val alertView = LayoutInflater.from(UpdatePackQtyActivity@ this)
//                    .inflate(R.layout.dialog_upate_qty, null)
//                val show = alertDialog.setView(alertView)
//                    .show()
//                alertView.btnPackQtyDialog.setOnClickListener {
//
//                    if (TextUtils.isEmpty(alertView.edPackQtyDialog.text.toString())) {
//                        showToast(getString(R.string.text_input_qyt))
//                        return@setOnClickListener
//
//                    } else if(TextUtils.isEmpty(alertView.edPackWeigthDialog.text.toString())){
//                        showToast("请填写重量")
//                        return@setOnClickListener
//                    }else if(TextUtils.isEmpty(alertView.edPackGangDialog.text.toString())){
//                        showToast("请输入缸号")
//                        return@setOnClickListener
//                    }else {
//                        show.dismiss()
//                        showLoading()
//                        getPackModel?.postPackQty(packId, alertView.edPackQtyDialog.text.toString(),alertView.edPackWeigthDialog.text.toString(),alertView.edPackGangDialog.text.toString())
//                    }
//                }
//
//
//            } else {
//                showToast(getString(R.string.text_input_scan_card))
//                return@setOnClickListener
//            }
            val inputEditTextField = EditText(this)
            inputEditTextField.inputType= InputType.TYPE_CLASS_NUMBER
            val dialog = android.app.AlertDialog.Builder(this)
                .setTitle("")
                .setMessage("请输入数量")
                .setView(inputEditTextField)
                .setPositiveButton("确定") { _, _ ->
                    val editTextInput = inputEditTextField .text.toString()
                    if (editTextInput.isEmpty()) {
                        showToast("请输入数量")
                        return@setPositiveButton
                    }
                    setPaiZaiProducedQty(editTextInput);

                }
                .setNegativeButton("取消", null)
                .create()
            dialog.show()



        }
    }


    fun setPaiZaiProducedQty(editTextInput:String){
        getPackModel?.setPaiZaiProducedQty(paiZaiBean?.id.toString(),editTextInput,scrapsFlag)

    }





    /**
     * 请求数据
     */
    private fun requestData() {
        getPackModel?.loadGetPackById(packId)
    }

    /**
     * 初始化刷卡器
     */
    private fun initCardReader() {

        readCardUtils?.setReadSuccessListener(ReadCardUtils.OnReadSuccessListener() {
            Log.e("zhangyucode", "barcode: " + it);
            if (it.length == 8 || it.length == 10) {
                //叫唤
                val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                val r = RingtoneManager.getRingtone(applicationContext, notification)
                r.play()
//                val soundPool = SoundPool(2, AudioManager.STREAM_MUSIC, 0)
//                soundPool.load(this,R.raw.ondo,1)
//                soundPool.play(1,1f, 1f, 0, 0, 1f);
//                showLoading()
                recordViewModel?.loadPackDataByRFRDUpdate(it)

            }
        });
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val code = data?.getStringExtra(CompanionType.INTENT_EXTRA_QRCODE)
        if (resultCode == Activity.RESULT_OK) {
            //根据二维码查包
            showLoading()
           // recordViewModel?.loadPackDataUpdate(qrCode)
            qrCode=code
            getPackModel?.paiZaiInfo(qrCode!!)

        }
    }


    @NeedsPermission(Manifest.permission.CAMERA)
    fun showCamera() {
        try {
            startActivityForResult(Intent(this, QrScanActivity::class.java), 0)

        } catch (e: Exception) {
            Log.e("activity", e.toString())
        }
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    fun showRationaleForCamera(request: PermissionRequest) {
        request.proceed();
        Log.e("permission", "OnShowRationale")
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    fun onCameraDenied() {
        showCameraWithPermissionCheck()
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    fun onCameraNeverAskAgain() {
//        showToast("请到设置打开相机权限")
        SystemActivityUtil.getAppDetailSettingIntent(this)
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)

    }

    /**
     * 刷卡数据监听
     */
    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        if (ReadCardUtils.isInputFromReader(this, event)) {
            if (readCardUtils != null) {
                readCardUtils?.resolveKeyEvent(event);
            }
        }
        return super.dispatchKeyEvent(event);

    }

    override fun onDestroy() {
        readCardUtils?.removeScanSuccessListener();
        readCardUtils = null;
        super.onDestroy()
    }

}
